package com.example.testproj.webview;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.example.testproj.R;

public class WebViewTestActivity extends AppCompatActivity {
    private Handler handler = new Handler();
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view_test);

        webView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);

        webView.loadUrl("http://192.168.1.1/");
//        webView.loadData("","text/html","UTF-8");

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);


//                //编写 javaScript方法
                String javascript =  "javascript:function hideOther() { alert(\"这是测试\");}";

                //创建方法
                view.loadUrl(javascript);

                webView.loadUrl("javascript:hideOther()");
                //加载方法

                Log.d("qin", "onPageFinished: " + url);

            }
        });

        webView.setWebChromeClient(new MyWebChromeClient());
    }

    private  class MyWebChromeClient extends WebChromeClient {

        @Override

        public boolean onConsoleMessage(ConsoleMessage cm) {

            Log.d("test", cm.message() + " -- From line "+ cm.lineNumber() + " of "+cm.sourceId());

            return true;

        }

        @Override

        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

            Toast.makeText(WebViewTestActivity.this, message, Toast.LENGTH_SHORT).show();

            return true;

        }
    }
}
